import 'package:flui/flui.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:fzcgx_app/ui/base/base_stateful_widget.dart';
import 'package:fzcgx_app/ui/base/base_view_model.dart';

import 'package:provider/provider.dart';


class ProviderWidget<T extends BaseViewModel> extends BaseStatefulWidget {
  final Widget Function(BuildContext context, T value, Widget child) builder;
  final T model;
  final Widget child;
  final Function(T) onReady;

  /// 是否内部自动分别处理State状态
  final bool autoState;

  ProviderWidget({
    this.model,
    this.child,
    this.onReady,
    this.builder,
    this.autoState = true,
  });

  @override
  State<StatefulWidget> createState() => _ProviderWidgetState<T>();
}

class _ProviderWidgetState<T extends BaseViewModel>
    extends State<ProviderWidget<T>> {
  @override
  void initState() {
    super.initState();
    if (widget.onReady != null) {
      widget.onReady(widget.model);
    }
  }

  @override
  Widget build(BuildContext context) {
    var content = Consumer<T>(builder: widget.builder, child: widget.child);

    return ChangeNotifierProvider<T>(
      create: (_) => widget.model,
      child: widget.autoState
          ? Stack(
              children: <Widget>[
                content,
                Consumer<T>(
                  builder: (context, data, child) {
                    return _getStatePage(data.state);
                  },
                ),
              ],
            )
          : content,
    );
  }

  Widget _getStatePage(ViewState state) {
    return Offstage(
      offstage: state == ViewState.Success,
      child: state == ViewState.Loading
          ? _loadingWidget()
          : (state == ViewState.Empty
              ? _emptyWidget()
              : (state == ViewState.Error ? _errorWidget() : Container())),
    );
  }

  Widget _loadingWidget() {
    return Center(
      child: CupertinoActivityIndicator(
        animating: true,
        radius: 20,
      ),
    );
  }

  Widget _emptyWidget() {
    return FLEmptyContainer(
      backgroundColor: Colors.white,
      image: Image.asset('assets/images/delete.png',),
      title: "暂时没有数据...",
    );
  }

  Widget _errorWidget() {
    return FLEmptyContainer(
        title: '加载失败',
        detailText: '接受我的膝盖，原谅我的伤害，请您稍后重试!',
        space: 12,
        actionButton: Container(
          width: 150,
          height: 35,
          child: RaisedButton(
            textColor: Colors.white,
            child: Text('重试'),
            onPressed: () => {
              if (widget.model != null) {widget.model.onReTry()}
            },
          ),
        ));
  }
}